# coding=utf-8
#


import os
import sys
import json
import time
from datetime import datetime

from django.conf import settings

from django.core.management.base import BaseCommand

from iminer.utils import check_pid

from iminer.agent.models import Agent
from iminer.agent.models import AgentHeartbeat
from iminer.utils.redis import redis_proxy

from iminer.sm_log import getLogger


logger = getLogger("iminer.agent.management.commands.cron_sync_agent_info")


class Command(BaseCommand):
    help = "定时遍历agent，发现异常agent"

    def handle(self, *args, **options):
        """ 定时遍历agent，发现异常agent """
        task_name = "pid/cron_sync_agent_info"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            counter = 0
            while 1:
                try:
                    hb_info = redis_proxy.r.lpop(settings.DATA_QUEUE)
                    if not hb_info:
                        counter += 1
                        if counter >= 100:
                            sys.exit(1)

                        time.sleep(3)
                    else:
                        #logger.info("Got HBInfo: %s" % hb_info)
                        data = json.loads(hb_info)

                        # {'log_time': '2024-06-29 07:43:00', 'local_its': 6, 'local_avg_its': 6, 'cpu': 2, 'alias': 'ecs-c53d', 'idc': 'huawei'}

                        alias = data.get("alias", "")
                        idc = data.get("idc", "")
                        cpu = data.get("cpu", 0)
                        local_its = data.get("local_its", 0)
                        local_avg_its = data.get("local_avg_its", 0)
                        source = data.get("source", "") or "qm"
                        ip = data.get("ip", "")

                        #agent, _ = Agent.objects.get_or_create(alias=alias, status=1)
                        #agent, _ = Agent.objects.get_or_create(alias=alias)
                        if idc == "hw":
                            agent, _ = Agent.objects.get_or_create(ip=ip)
                            agent.alias = alias
                        elif idc == "huoshan":
                            agent, _ = Agent.objects.get_or_create(alias=alias)
                            agent.ip = ip
                        elif idc == "tencent":
                            agent, _ = Agent.objects.get_or_create(alias=alias)
                            agent.ip = ip

                        agent.idc = idc
                        agent.cpu = cpu
                        agent.local_its = local_its
                        agent.local_avg_its = local_avg_its
                        agent.status = 1

                        if local_its or local_avg_its:
                            agent.last_active = datetime.now()
                            """
                            AgentHeartbeat(alias=alias,
                                           local_its=local_its,
                                           ip=ip,
                                           cpu=cpu,
                                           local_avg_its=local_avg_its,
                                           cur_time=datetime.now()).save()
                            """

                        agent.save()
                except Exception as msg:
                    print(str(msg))
                    time.sleep(3)
